package com.cirnoworks.guice.impl;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import javax.inject.Singleton;

import com.cirnoworks.guice.LifeCycleService;
import com.cirnoworks.guice.LifeCycle;

@Singleton
public class LifeCycleServiceImpl implements LifeCycleService {
	private ArrayList<WeakReference<LifeCycle>> registions = new ArrayList<WeakReference<LifeCycle>>();
	private boolean dead = false;

	@Override
	public synchronized void register(LifeCycle lifeCycleSupport) {
		if (dead) {
			throw new RuntimeException("LifeCycle is currently dead.");
		} else {
			registions
					.add(new WeakReference<LifeCycle>(lifeCycleSupport));
			lifeCycleSupport.startup();
		}
	}

	@Override
	public synchronized void onShutdown() {
		dead = true;
		for (WeakReference<LifeCycle> ref : registions) {
			LifeCycle lifeCycleSupport = ref.get();
			if (lifeCycleSupport != null) {
				lifeCycleSupport.shutdown();
			}
		}
		registions = null;

	}

}
